package be.pluyckx.batteryprogress.database;

import android.content.Context;

import java.io.IOException;

import be.pluyckx.batteryprogress.data.Observer;
import be.pluyckx.batteryprogress.data.history.BatteryHistory;

/**
 * Created by Philip Luyckx on 3/08/13.
 */
public abstract class BatteryHistoryDatabase implements Observer {
  private final Context mContext;
  private final BatteryHistory mBatteryHistory;

  public BatteryHistoryDatabase(Context context, BatteryHistory batteryHistory) {
    mContext = context.getApplicationContext();
    mBatteryHistory = batteryHistory;
    mBatteryHistory.addObserver(this);
  }

  public void destroy() {
    mBatteryHistory.removeObserver(this);
  }

  protected Context getContext() {
    return mContext;
  }

  protected BatteryHistory getBatteryHistory() {
    return mBatteryHistory;
  }

  public abstract void read() throws IOException;

  public abstract void clear() throws IOException;

  protected abstract void onItemAdded(int start, int end);

  protected abstract void onItemRemoved(int start, int end);

  protected abstract void onItemUpdated(int start, int end);

  @Override
  public void onDataChanged(Object observable, ChangeInfo info) {
    if (observable == mBatteryHistory) {
      BatteryHistory.ChangeInfo i = (BatteryHistory.ChangeInfo) info;
      switch (i.action) {
        case BatteryHistory.ChangeInfo.ACTION_ADD:
          onItemAdded(i.start, i.end);
          break;
        case BatteryHistory.ChangeInfo.ACTION_REMOVE:
          onItemRemoved(i.start, i.end);
          break;
        case BatteryHistory.ChangeInfo.ACTION_UPDATE:
          onItemUpdated(i.start, i.end);
          break;
      }
    }
  }
}
